#!/user/bin/perl -w
#-w ?
# global variables
$menu_choice = "";
$title_file="title.cbd";
$tracks_file = "tracks.cbd";
$temp_file = "/tmp/cdb.$$";
$SIG{INT} = sub { tidy_up(); exit; };

sub read_in{
	open TITLES, $title_file
		or die "Could not open $title_file $!\n"; #$! chua thong bao loi cua open
	while(<TITLES>) {
		chomp;
		push @titles, $_;
	}
	close TITLES;

	open TRACKS, $tracks_file
		or die "Could not open $tracks_file : $!\n";

	while(<TRACKS>) {
		chomp;
		push @tracks, $_;
	}
	close TRACKS;
}

sub tidy_up {
	open TITLES, ">". $title_file
		or die "Could not write to $title_file : $!\n";
	foreach(@titles) {
		print TITLES "$_\n";
	}
	close TITLES;

	open TRACKS, ">".$tracks_file
		or die "Could not write to file : $!\n";
	while(@tracks) {
		print TRACKS "$_\n";
	}
	close TRACKS;
}

# ham doc du lieu tu ban phim
sub get_return {
	print "press return";
	<> #doc mot dong trang tu STDIN va bo qua
}

sub get_confirm {
	print "Are you sure?";
	while(1) {
		$_ = <>; # doc ket qua do nguoi dung nhap vao va luu vao $_
		return 1 if(/^y(?:es)?$/i); # 1 la true, 0 la false ?
		if(/^no?$/i) {
			print "Cancelled!\n";
			return 0;
		}
		print "Please enter yes or no.\n";
	}
}

# hien thi main menu va yeu cau nguoi dung chon
# su dung ki thuat tai lieu here cua shell. Linh in se in toan bo noi dung
# bat day tu <<EOF cho den khi gap lai ki heu EOF

sub set_menu_choice {
	print `clear`; # cach goi lenh he thong bang cap nhay nguoc

	#print <<EOF;
	print "a) Add new CD\n";
	print "f) Find CD\n";
	print "c) count the CDs and tracks in the catalog\n";
	#EOF
	if($cdcatnum) {
		print "  l) List tracks on $cdtitle\n";
		print "  r) Remove $cdtitle\n";
		print "  u) Update track information for $cdtitle\n";
	}

	print "  q) Quit \n\n";
	print "Please enter choise then press return\n";
	chomp ($menu_choice=<>);
	return;
}

# them recode va thong tin ve track vao mang
sub insert_title{
	push @titles, (join ",", $_);
}

sub insert_track{
	push @tracks, (join ",", $_);
}

sub add_record_track {
	print "Enter track information for this CD\n";
	print "When no more tracks enter q\n";
	$cdtrack=1;
	$cdtitle="";

	while($cdtitle ne "q") {
		print "Track $cdtrack, track title? ";
		chomp($cdtitle=<>);

		if($cdtitle=~/,/) {
			print "Sorry, no commas allowed.\n";
			redo; # ??
		}

		if($cdtitle and $cdtitle ne "q") {
			insert_track($cdcatnum, $cdtrack, $cdtitle);
			$cdtrack++;
		}
	}
}

# cai dat ham add_records de them CD vao co so du lieu
sub add_records {
	print "Enter catalog name ";
	chomp($cdcatnum=<>);
	$cdcatnum=~s/,.*//;

	print "Enter title";
	chomp($cdtitle=<>);
	$cdtitle=~s/,.*//;

	print "Enterr type ";
	chomp($cdtype=<>);
	$cdtype=~s/,.*//;

	print "Enter artist/composer";
	chomp($cdac=<>);
	$cdac=~s/,.*//;

	print "About to add a new entry\n";
	print "$cdcatnum $cdtitle $cdtype $cdac\n";

	if(get_confirm()) {
		insert_title($cdcatnum, $cdtype, $cdtype, $cdac);
		add_record_tracks();
	} else {
		remove_records();
	}
}

# boi vi chung ta da co 1 mang du lieu, viec tim kiem tro nen don gian hon
sub find_cd {
	$asklist = ($_[0] ne "n");

	$cdcatnum="";
	print  "Enter string for search in the CDtitles ";
	chomp($searchstr=<>);
	return 0 unless $searchstr;

	@matchs = grep /\Q$searchstr\E/, @titles;
	if(scalar @matchs==0) {
		print "Sorry nothing found. \n";
		get_return();
		return 0;
	} elsif(scalar @matchs!=1){
		print "Sorry, not unique.\n";
		print "Found the following: \n";
		foreach(@matchs) {
			print "$_\n";
		}
		get_return();
		return 0;
	}

	($cdcatnum, $cdtitle, $cdtype, $cdac) = split ",", $matchs[0];
	unless ($cdcatnum) {
		print "Sorry, could not extract catalog field\n";
		get_return();
		return 0;
	}

	print "\nCatalog number: $cdcatnum\n";
	print "Title: $cdtitle\n";
	print "Type: $cdtype";
	print "Artist/Composer: $cdac\n\n";
	get_return();

	if($asklist){
		print "View tracks for this CD? ";
			$_=<>;
		if(/^y(?:es)?$/i){
			print "\n";
			list_tracks();
			print "\n";
		}
	}
	return 1;
}

# ham cap nhat thong tin ve cd
sub update_cd {
	unless ($cdcatnum) {
		print "You must select a CD first\n";
		find_cd("n");
	}
	if($cdcatnum) {
		print "Current tracks a CD first\n";
		list_tracks();
		print "\nThis will re-enter the track for $cdtitle\n";
		if(get_confirm()) {
			@tracks=grep !/^$cdcatnum,/, @tracks;
			add_record_tracks();
		}
	}
}

#dem so CD trong mang
sub count_cds{
	print "Found ". (scalar @titles) ."CDs, ";
	print "with a total of ".(scalar @tracks) . " tracks\n";
	get_return();
}

# xoa CD
sub remove_record {
	unless ($cdcatnum) {
		print "You must select a CD first\n";
		find_cd("n");
	}

	if($cdcatnum) {
		print "You are about to delete $cdtitle\n";
		if(get_confirm()) {
			@titles = grep !/^$cdcatnum,/, @titles;
			@tracks = grep !/^$cdcatnum,/, @tracks;
			$cdcatnum="";
			print "Entry removed";
		}
		get_return();
	}
}

# liet ke track phai xem yeu cau tung trang vi vay ta can ghi ket xuat ra file tam
sub list_tracks{
	unless($cdcatnum) {
		print "No CD selected yet.\n";
		return ;
	}
	open (TEMP, ">$temp_file")
		or die "Can't write to $temp_file: $!\n";

	@temp = grep /^$cdcatnum,/, @tracks;
	if(scalar @temp == 0) {
		print "No tracks found for $cdtitle";
	} else {
		print TEMP "\n$cdtitle : \n\n";
		foreach(@temp) {
			s/^.*?,//; #xoa field dau tien
			print TEMP $_."\n";
		}
		close TEMP;
		system("more $temp_file");
		unlink($temp_file); # delete if
	}
	get_return();
}

# phai ghi lai noi dung cua mang tro lai file truoc khi chuong trinh ket thuc
# kiem tra va tao file moi neu chua co
system("touch $title_file") unless ( -f $title_file );
system("touch $tracks_file") unless ( -f $tracks_file );

read_in();
system("clear");
print "\nMiniCD manager\n";
#sleep(2);

while(1) {
	set_menu_choice();
	if($menu_choice=~/a/i) {add_records();}
	elsif($menu_choice=~/r/i) { remove_records(); }
	elsif($menu_choice=~/f/i) { find_cd("y"); }
	elsif($menu_choice=~/u/i) { update_cd(); }
	elsif($menu_choice=~/c/i) { count_cds(); }
	elsif($menu_choice=~/l/i) { list_tracks(); }
	elsif($menu_choice=~/b/i) {
		print "\n";
		foreach(@titles) {
			print "$_\n";
		}
		print "\n";
		get_return();
	}
	elsif($menu_choice=~/q/i) { last; }
	else { print "Sorry, choice not recognized .\n"; }
}

tidy_up();
exit;
